<template>
  <view class="router-view bcl-active container">
    <view class="fz-15 bold mb-15 mt-15">输入您的新昵称</view>

    <view class="uni-input">
      <input
        type="text"
        placeholder="请输入昵称"
        :focus="true"
        v-model="nickname"
      />
    </view>

    <view class="tips cl-basic"
      >昵称可使用汉子、字母、数字或者下划线,长度在2-24个字符,一个汉字为2个字符</view
    >

    <button
      class="uni-button uni-button-lg uni-button-full mt-50"
      @tap="saveNickname"
    >
      保存
    </button>
  </view>
</template>

<script>
import { mapState, mapActions } from "vuex";
import { editNickname } from "@/apis/user";

export default {
  data() {
    return {
      nickname: "",
    };
  },

  methods: {
    /**
     * 保存昵称
     */
    async saveNickname() {
      let strLen = this.nickname.replace(/[^\u0000-\u00ff]/g, "aa").length;
      if (strLen < 2 || strLen > 24) return this.$toast("昵称长度不符合");
      let params = {
        nickname: this.nickname,
      };

      let { code, data } = await editNickname(params);
      if (code === 200) {
        let userInfo = {
          ...this.userInfo,
          nickname: this.nickname,
        };
        this.SET_USER_INFO(userInfo);
        this.$toast("修改成功");
        setTimeout(() => {
          uni.navigateBack();
        }, 500);
      }
    },

    ...mapActions(["SET_USER_INFO"]),
  },

  computed: {
    ...mapState(["userInfo"]),
  },
};
</script>
